import React, { useState, useEffect, useRef, useCallback } from 'react';
import Header from "../../components/Header/Header.tsx";
import CommunityPost from '../../components/CommunityPost';
import { CommunityPost as PostType, CommunityCategory } from '../../types/community';
import { Tabs, Skeleton, message, Empty, Button } from 'antd';
import { listPostByPage } from '../../api/communityPostController';
import { listCategories } from '../../api/communityCategoryController';
import { listCommunityTags } from '../../api/communityTagController';
import { useNavigate } from 'react-router-dom';

const { TabPane } = Tabs;
const POSTS_PER_PAGE = 8;

const BookCommunity: React.FC = () => {
  const [activeCategory, setActiveCategory] = useState<string>('');
  const [categories, setCategories] = useState<CommunityCategory[]>([]);
  const [posts, setPosts] = useState<PostType[]>([]);
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const loadingRef = useRef<HTMLDivElement>(null);
  const [initialLoading, setInitialLoading] = useState(true);
  const navigate = useNavigate();

  // 加载分类
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await listCategories();
        if (response.code === 200 && response.data) {
          setCategories(response.data);
          if (response.data.length > 0) {
            setActiveCategory(response.data[0].categorycode);
          }
        }
      } catch (error) {
        console.error('Failed to load categories:', error);
      }
    };
    fetchCategories();
  }, []);

  // 加载帖子数据
  const loadPosts = useCallback(async (pageNum: number) => {
    if (!activeCategory) return;
    
    try {
      const response = await listPostByPage({
        current: pageNum,
        pageSize: POSTS_PER_PAGE,
        categorycode: activeCategory,
        title: "",
        createuser: 0
      });

      if (response.code === 200 && response.data) {
        // 只保留已审核的帖子
        const filteredPosts = response.data.records.filter(post => post.auditstatus === 1);
        
        if (pageNum === 1) {
          setPosts(filteredPosts);
        } else {
          setPosts(prev => [...prev, ...filteredPosts]);
        }
        // 根据过滤后的数组长度判断是否还有更多数据
        setHasMore(filteredPosts.length === POSTS_PER_PAGE);
      }
    } catch (error) {
      console.error('Failed to load posts:', error);
    } finally {
      setLoading(false);
      setInitialLoading(false);
    }
  }, [activeCategory]);

  useEffect(() => {
    if (activeCategory) {
      setInitialLoading(true);
      setPage(1);
      loadPosts(1);
    }
  }, [activeCategory, loadPosts]);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !initialLoading && !loading && hasMore) {
          loadPosts(page + 1);
          setPage(prev => prev + 1);
        }
      },
      { threshold: 0.1 }
    );

    if (loadingRef.current) {
      observer.observe(loadingRef.current);
    }

    return () => observer.disconnect();
  }, [loadPosts, initialLoading, loading, hasMore, page]);

  const handleCategoryChange = (categoryCode: string) => {
    setActiveCategory(categoryCode);
    setPosts([]);
    setPage(1);
    setHasMore(true);
  };

  // 刷新当前页面的帖子列表
  const refreshCurrentPage = useCallback(async () => {
    if (!activeCategory) return;
    
    try {
      setLoading(true);
      const response = await listPostByPage({
        current: page,
        pageSize: POSTS_PER_PAGE,
        categorycode: activeCategory,
        title: "",
        createuser: 0
      });

      if (response.code === 200 && response.data) {
        // 只保留已审核的帖子
        const filteredPosts = response.data.records.filter(post => post.auditstatus === 1);
        
        setPosts(prev => {
          const newPosts = [...prev];
          // 更新当前页的数据
          const startIndex = (page - 1) * POSTS_PER_PAGE;
          filteredPosts.forEach((post: PostType, index: number) => {
            newPosts[startIndex + index] = post;
          });
          return newPosts;
        });
      }
    } catch (error) {
      console.error('Failed to refresh posts:', error);
      message.error('刷新列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [activeCategory, page]);

  const renderSkeletons = () => {
    return Array(POSTS_PER_PAGE).fill(null).map((_, index) => (
      <div key={index} className="bg-white rounded-lg p-6 mb-6">
        <Skeleton
          avatar
          active
          paragraph={{
            rows: 4,
          }}
        />
      </div>
    ));
  };

  return (
    <div className="min-h-screen flex flex-col bg-gray-50">
      <Header />
      <div className="flex-1">
        <div className="max-w-6xl mx-auto px-4 py-6">
          <Tabs
            activeKey={activeCategory}
            onChange={handleCategoryChange}
            className="community-tabs"
            tabBarGutter={8}
          >
            {categories.map(category => (
              <TabPane 
                tab={
                  <span className="px-6 py-3 text-base font-medium rounded-lg">
                    {category.categorynamezh}
                  </span>
                } 
                key={category.categorycode}
              >
                <div className="grid gap-6 mt-6">
                  {initialLoading ? (
                    renderSkeletons()
                  ) : posts.length > 0 ? (
                    <>
                      {posts.map((post) => (
                        <CommunityPost 
                          key={post.id} 
                          post={post}
                          sectionId={activeCategory}
                          onRefreshList={refreshCurrentPage}
                        />
                      ))}
                      {hasMore && <div ref={loadingRef} className="h-4" />}
                    </>
                  ) : (
                    <div className="flex justify-center items-center py-16">
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                          <span className="text-gray-500">
                            暂无内容，快来发布第一篇帖子吧！
                          </span>
                        }
                      >
                        <Button 
                          type="primary"
                          onClick={() => navigate('/create-post')}
                        >
                          发布帖子
                        </Button>
                      </Empty>
                    </div>
                  )}
                </div>
              </TabPane>
            ))}
          </Tabs>
        </div>
      </div>
    </div>
  );
};

export default BookCommunity; 